package com.hanter.android.radlib.util;

import android.app.ActivityManager;
import android.content.Context;
import android.os.Process;

import androidx.annotation.Nullable;

import java.util.List;

public class ProcessUtils {

    public static final String TAG = ProcessUtils.class.getSimpleName();

    /**
     * 杀进程
     */
    public static void killProcess(int pid) {
        if (pid > 0)
            Process.killProcess(pid);
    }

    /**
     * 退出当前进程
     */
    public static void killProcess() {
        System.exit(0);
    }

    @Nullable
    public static String getCurrentProcessName(Context context) {
        int pid = Process.myPid();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (am != null)
            for (ActivityManager.RunningAppProcessInfo appProcess : am.getRunningAppProcesses()) {
                if (appProcess.pid == pid) {
                    return appProcess.processName;
                }
            }
        return null;
    }

    /**
     * 多进程情况下，判断是不是主进程，只在主进程中进行初始化操作
     */
    public static boolean isMainProcess(Context context) {
        ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
        if (am != null) {
            List<ActivityManager.RunningAppProcessInfo> processInfo = am.getRunningAppProcesses();
            String mainProcessName = context.getPackageName();
            int myPid = Process.myPid();
            for (ActivityManager.RunningAppProcessInfo info : processInfo) {
                if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                    return true;
                }
            }
        }
        return false;
    }

}
